package com.chaber.containers.presenters;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.TreeItem;

import org.springframework.beans.factory.annotation.Autowired;

import com.chaber.containers.beans.ProductCategoryData;
import com.chaber.containers.services.ProductCategoryService;
import com.chaber.containers.views.ProdCatListView;

public class ProdCatListPresenter extends AbstractPresenter {

	@Autowired
	private ProdCatListView prodCatListView;
	
	@Autowired
	private ProductCategoryService productCategoryService;

	@Override
	public void bindViewActions() {
		this.prodCatListView.setOnSelectionChanged(new EventHandler<Event>() {
			@Override
			public void handle(Event evt) {
				if (prodCatListView.isSelected()) {
					buildTreeView();
					prodCatListView.deactivateActionButtons();
				}
			}
		});
	}

	public void buildTreeView() {
		List<ProductCategoryData> result = this.productCategoryService.findAll();

		TreeItem<ProductCategoryData> rootItem = this.prodCatListView.getProdCategoriesTree().getRoot();
		rootItem.getChildren().clear();
		
		Set<Integer> addedCategories = new HashSet<>();
		for (ProductCategoryData pCat : result) {
			if (!addedCategories.contains(pCat.getId())) {
				this.buildTreeItem(pCat, rootItem, addedCategories);
			}
		}
	}

	private void buildTreeItem(ProductCategoryData productCat, TreeItem<ProductCategoryData> rootItem, Set<Integer> addedCategories) {
		TreeItem<ProductCategoryData> currRoot = new TreeItem<ProductCategoryData>(productCat);
		currRoot.setExpanded(true);

		addedCategories.add(productCat.getId());

		for (ProductCategoryData pCat : productCat.getChildCategories()) {
			if (!addedCategories.contains(pCat.getId())) {
				this.buildTreeItem(pCat, currRoot, addedCategories);
			}
		}

		rootItem.getChildren().add(currRoot);
	}
}
